import path from 'node:path'
import type {
  UserConfig,
  ConfigEnv,
  ProxyOptions,
} from 'vite'
import {
  loadEnv,
  defineConfig,
} from 'vite'

import createVitePlugins from './vite/plugins'

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const {
    VITE_PORT,
    VITE_PROXY_URL,
    VITE_BASE_PATH,
    VITE_OUT_DIR,
  } = loadEnv(
    mode,
    process.cwd(),
  )

  let proxy: Record<string, string | ProxyOptions> = {}
  if (VITE_PROXY_URL) {
    proxy = {
      '/api': {
        target: VITE_PROXY_URL,
        changeOrigin: true,
      },
    }
  }

  return {
    base: VITE_BASE_PATH,
    plugins: createVitePlugins(mode),
    root: process.cwd(),
    resolve: { alias: { '@': path.resolve(__dirname, 'src') } },

    server: {
      port: Number(VITE_PORT),
      proxy,
      host: true,
    },
    build: { outDir: path.resolve(__dirname, VITE_OUT_DIR) },
  }
})
